#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QListWidgetItem>
#include <QClipboard>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_e_input_returnPressed()
{
    load_base64_data(ui->e_input->text());
}


void MainWindow::on_listWidget_itemClicked(QListWidgetItem *item)
{
    if (item) {
        QPixmap pixmap;
        pixmap.loadFromData(QByteArray::fromBase64(item->data(Qt::UserRole).toString().toUtf8()));
        ui->icon->setPixmap(pixmap);
    }
}


void MainWindow::on_btn_copy_clicked()
{
    auto item = ui->listWidget->currentItem();
    if (item)
    {
        auto item_widget = ui->listWidget->itemWidget(item);
        QPixmap pixmap;
        pixmap.loadFromData(QByteArray::fromBase64(item->data(Qt::UserRole).toString().toUtf8()));
        qApp->clipboard()->setPixmap(pixmap);
    }
}


void MainWindow::on_btn_paste_clicked()
{
    load_base64_data(qApp->clipboard()->text());
}

void MainWindow::load_base64_data(const QString &data)
{
    ui->listWidget->clear();

    // 
    auto inputs = data.split("\n", Qt::SkipEmptyParts);;
    int row = 0;
    foreach(auto var, inputs) {
        if (var.startsWith("data:image/png;base64,")) {
            var = var.replace("data:image/png;base64,","");
        }
        QPixmap pixmap;
        pixmap.loadFromData(QByteArray::fromBase64(var.toUtf8()));

        row ++;
        if (pixmap.isNull() == false) {
            auto item = new QListWidgetItem;
            item->setData(Qt::UserRole, var);
            item->setIcon(QIcon(pixmap));
            item->setText(QString("第 %1 条数据").arg(row));
            ui->listWidget->addItem(item);
        } else {
            auto item = new QListWidgetItem;
            item->setData(Qt::UserRole, var);
            item->setIcon(QIcon(pixmap));
            item->setText(QString("第 %1 条数据 - 异常").arg(row));
            ui->listWidget->addItem(item);
        }
    }
}


void MainWindow::on_btn_next_clicked()
{
    auto item = ui->listWidget->currentItem();
    if (item)
    {
        auto item_row = ui->listWidget->row(item);
        ui->listWidget->setCurrentRow(item_row+1);
        on_listWidget_itemClicked(ui->listWidget->currentItem());
    }
}

